﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AiXiu.BLL;
using AiXiu.IBLL;
using AiXiu.Model;
using AiXiu.Common;
using System.IO;

namespace AiXiu.WebSite
{
    public partial class UploadAvatar : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string userAvatar = IdentityManager.ReadUser().Avatar;
                if (string.IsNullOrWhiteSpace(userAvatar))
                {
                    imgExhibitAvatar.ImageUrl = "~/imgs/avatar.jpg";
                }
                else
                {
                    imgExhibitAvatar.ImageUrl = userAvatar;
                }
            }
        }

        private bool FileUploadIsImg(string fileUrl)
        {
            string fileType = fileUrl.Substring(fileUrl.LastIndexOf(".") + 1);
            string[] typeArr = { "png", "jpg", "jpeg" };
            foreach (string item in typeArr)
            {
                if (item.Equals(fileType)) return true;
            }
            return false;
        }

        protected void btnUploadAvatar_Click(object sender, EventArgs e)
        {
            if (FileUploadAvatar.HasFile && FileUploadIsImg(FileUploadAvatar.FileName))
            {
                int userId = IdentityManager.ReadUser().Id;
                string saveUrl = Server.MapPath(string.Format("~/Avatar/{0}/", userId));

                Directory.CreateDirectory(saveUrl);
                FileUploadAvatar.SaveAs(saveUrl + FileUploadAvatar.FileName);

                imgExhibitAvatar.ImageUrl = string.Format("/Avatar/{0}/{1}", userId, FileUploadAvatar.FileName);
            }
            else
            {
                this.Alert("noImg", "未选择图片或图片格式不正确！");
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            TBUsers newUser = IdentityManager.ReadUser();
            newUser.Avatar = imgExhibitAvatar.ImageUrl;
            OperResult rest = new UserManager().editAvatar(newUser);

            if (rest.StatusCode == StatusCode.Succeed)
            {
                IdentityManager.SaveUser(newUser);
                this.Redirect("editSuccee", "Personal.aspx");
            }
            else
            {
                this.Alert("editFail", rest.Message);
                File.Delete(rest.Message);
            }
        }
    }
}